//
//  XBEmoticonManager.swift
//  EmotionKeyboardDemo
//
//  Created by mac on 15/12/26.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit

class XBEmoticonManager: NSObject {
    
    static let sharedManager = XBEmoticonManager()
    
    // 定义外部模型属性
    var packges = [XBEmoticonPackge]()

    override init() {
        super.init()
        loadEmoticonPackge()
    }
    
    // MARK: 加载表情数据
    private func loadEmoticonPackge() {
        let path = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + "emoticons.plist"
        let dict = NSDictionary(contentsOfFile: path)!
        if let array = dict["packages"] as? [[String : AnyObject]] {
            // 遍历数组
            for item in array {
                let id = item["id"] as! String
                // 根据id路径去加载不同路径下地plist文件
                loadPlist(id)
            }
        }
    }
    
    private func loadPlist(id: String) {
        let path = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + id + "/info.plist"
        let dict = NSDictionary(contentsOfFile: path)!
        // 取出表情名字
        let emoticonName = dict["group_name_cn"] as! String
        // 取出表情数组
        let emoticonArr = dict["emoticons"] as! [[String : String]]
        let p = XBEmoticonPackge(idPath: id, emoticonName: emoticonName, emoticonsArr: emoticonArr)
        packges.append(p)
    }
    
    func statusTextToImageText(str: String, font: UIFont) ->NSAttributedString {
        // 用正则表达式来获取里面的表情文字,然后再去取出对应的表情图片,然后再转换成富文本展示在cell上
        // 规则
        let pattern = "\\[.*?\\]"
        let regx = try! NSRegularExpression(pattern: pattern, options: [])
        // 结果集
        let results = regx.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))
        // 倒叙,取出表情文字
        var index = results.count - 1
        let strM = NSMutableAttributedString(string: str)
        while index >= 0 {
            let result = results[index]
            let range = result.rangeAtIndex(0)
            let subStr = (str as NSString).substringWithRange(range)
            // 去表情库里查找图片
            if let emoticon = getEmoticonWithString(subStr) {
                // 获取表情富文本
                let imageAttach = XBEmoticonAttachment(emoticon: emoticon).imageText(font)
                // 将上面范围内的字符串转换成富文本
                strM.replaceCharactersInRange(range, withAttributedString: imageAttach)
            }
            index--
        }
        return strM
    }
    
    func getEmoticonWithString(str: String) ->XBEmoticon? {
        let packgeArr = XBEmoticonManager.sharedManager.packges
        // 遍历表情包
        for packge in packgeArr {
            // 筛选表情包里的表情数组
            let emoticons = packge.emoticons.filter({ (emo) -> Bool in
                // 如果和传进来的名字一样就返回true
                return emo.chs == str
            })
            if emoticons.count != 0 {
                return emoticons.last
            }
        }
        return nil
    }
}
